package com.example.demo.controller;

import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import jakarta.servlet.http.HttpServletRequest;

@Controller
public class CustomErrorController implements org.springframework.boot.web.servlet.error.ErrorController {

    @RequestMapping("/error")
    @ResponseBody
    public ResponseEntity<String> handleError(HttpServletRequest request) {
        // 获取错误状态码
        Object status = request.getAttribute("jakarta.servlet.error.status_code");
        int statusCode = status != null ? Integer.parseInt(status.toString()) : 404;

        // 直接返回JSON错误响应，避免重定向循环
        String errorJson = String.format(
                "{\"code\": %d, \"message\": \"%s\", \"data\": null}",
                statusCode,
                statusCode == 404 ? "请求路径不存在" : "服务器错误"
        );

        return ResponseEntity.status(statusCode)
                .header("Content-Type", "application/json")
                .body(errorJson);
    }
}